# -*- coding: utf-8 -*-
# @Time    : 2021/5/29 20:28
# @Author  : YIGE
# @Email   : yige@maqu.com
# @File    : tasks.py
# @Software: PyCharm
from yige_shopping.settings import EMAIL_HOST_USER
from django.core.mail import send_mail
from celery_tasks.celery_main import app
from django_redis import get_redis_connection

import logging

# 导入日志器，创建，命名
logger = logging.getLogger(__name__)

EMAIL_KEY_TEMPLATE = 'email:verification:%s'


@app.task(name='send_mail_task')
def send_mail_task(email, verification_code, duration):
    """
    发送邮箱验证码
    :param email: 收件人邮箱
    :param verification_code: 随机验证码
    :param duration: 有效时长
    :return:
    """
    email_param = {
        'subject': 'ONE-GO物网站验证码',
        'message': '',
        'html_message':
            f"""
                <h2>欢迎注册使用ONE-GO物网站</h2>
                <p>您的验证码为：<span style="color:red">{verification_code}</span></p>
                <p>注意：验证码有效时长为{duration}分钟</p>
            """,
        'from_email': EMAIL_HOST_USER,
        'recipient_list': [email],
    }
    try:
        res_email = send_mail(**email_param)
    except Exception as e:
        logger.error(f"邮件验证码发送[出错][email: {email}, message: {e}]")
    else:
        if res_email != 1:
            logger.warning(f"邮件验证码发送[失败][email: {email}]")
        else:
            cache = get_redis_connection(alias="verify_codes")  # 从verify_codes的redis连接池中获取一个redis连接对象
            cache.set(EMAIL_KEY_TEMPLATE % email,
                      verification_code, 60 * duration)  # 存储 key,value email:verification:yige@yige.com,123456

            cache_default = get_redis_connection()
            cache_default.set(email, '1', 60)

            logger.info(f"验证码邮件发送[正常][email: {email}, verification_code: {verification_code}]")
